<?php

namespace App\Http\Controllers;

use App\Models\UserGroup;
use App\Models\VolunteerGroup;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class VolunteerGroupController extends Controller
{
    public function __construct(Request $request)
    {
        $user = $request->user();

        if (!$user || $user->type != 2) {
            throw new \Exception('权限不足');
        }

        parent::__construct();
    }

    public function index(Request $request) {
        $perPage =$request->get('perPage', 10);
        $user = $request->user();
        $teamId = $user->team_id;
        $data = VolunteerGroup::with('volunteer')->where('user_id', '=', $user->id)->paginate($perPage)->toArray();


        $groupCounts = DB::table('user_group')
            ->select(DB::raw('count(volunteer_group_id) as group_cnt, volunteer_group_id as group_id'))
            ->groupby('volunteer_group_id')
            ->get();
        $groupMap = [];
        foreach ($groupCounts as $group) {
            $groupMap[$group->group_id] = $group;
        }

        foreach ($data['data'] as &$item) {
            if (isset($groupMap[$item['id']])) {
                $item['group_user_count'] = $groupMap[$item['id']]->group_cnt;
            }
        }
        return $this->returnJSON([
            'count' => $data['total'],
            'rows' => $data['data']
        ]);
    }

    public function store(Request $request) {
        $this->validate($request, [
            'name' => 'required'
        ]);
        $user = $request->user();
        $node = new VolunteerGroup();
        $data = array_only($request->all(), ['name']);
        if ($user->type == 2) {
            $data['user_id'] = $user->id;
            $data['team_id'] = $user->team_id;
        }
        $node->fill($data);
        if ($node->save()) {
            return $this->returnJSON(null, 0, '新增成功');
        }
        return $this->returnJSON(null, 0, '新增失败');
    }

    public function update(Request $request, $id) {
        $this->validate($request, [
            'name' => 'required'
        ]);
        $node = VolunteerGroup::findOrFail($id);
        $data = array_only($request->all(), ['name']);
        $node->fill($data);
        if ($node->save()) {
            return $this->returnJSON(null, 0, '修改成功');
        }
        return $this->returnJSON(null, 0, '修改失败');
    }

    public function destroy($id) {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        if (VolunteerGroup::whereIn('id', $ids)->delete()) {
            DB::table('user_group')->whereIn('volunteer_group_id', $ids)->delete();
            return $this->returnJSON($ids, 0, '删除成功');
        } else {
            return $this->returnJSON(null, 1, "删除失败");
        }

    }

    public function getName(Request $request) {
        $user = $request->user();
        $data = VolunteerGroup::where('user_id', '=', $user->id)->get()->toArray();
//        echo(gettype($data[0]));die();
        return $this->returnJSON([
            "options" => $this->str2options($data)
        ]);

    }

    public function addVol2Group(Request $request, $id) {
        $this->validate($request, [
            'volunteer_group_id' => 'required'
        ]);
        $ids = explode(',', $id);
        $groupId = $request->get('volunteer_group_id', '');
        $user = $request->user();
        $list = [];
        foreach ($ids as $i) {
            $node = UserGroup::where('volunteer_group_id', $groupId)->where('user_id', $i)->count();
            if ($node > 0) continue; // 过滤掉重复的
            $list[] = ['volunteer_group_id' => $groupId, 'team_id' => $user->team_id, 'user_id' => $i];
        }
        $res = DB::table('user_group')->insert($list);
        Log::info($res);

        if ($res) {
            return $this->returnJSON(null, 0, count($list) == count($ids) ? "添加成功" : "添加成功，已过滤重复添加的");
        } else {
            return $this->returnJSON(null, 1, "添加失败");
        }
    }

    public function remove(Request $request, $groupId, $userId) {
        $node = UserGroup::where('volunteer_group_id', $groupId)->where('user_id', $userId);
        if(!empty($node) && $node->delete()){
            return $this->returnJSON(null, 0, "移除成功");
        }
        return $this->returnJSON(null, 1, "移除失败");

    }

    protected function str2options($groupArr) {
        if (!isset($groupArr) || empty($groupArr)) {
            return [];
        }

        return array_map(function($item) {
            return [
                'label' => $item['name'],
                'value' => $item['id'],
            ];
        }, $groupArr);
    }
}
